package com.keyue.security.service;

import com.alibaba.fastjson.JSON;
import com.keyue.common.utils.EncryptUtils;
import com.keyue.common.utils.RedisUtil;
import com.keyue.common.utils.RequestStringUtils;
import com.keyue.security.config.SecurityProperties;
import com.keyue.security.vo.JwtUser;
import com.keyue.security.vo.OnlineUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Date 2019年10月26日21:56:27
 */
@Service
@Slf4j
public class OnlineUserService {

    @Resource
    private SecurityProperties properties;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 保存在线用户信息
     *
     * @param jwtUser /
     * @param token   /
     */
    public void save(JwtUser jwtUser, String token) {
        // 1. obtain request
        final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String email = jwtUser.getEmail();
        String phone = jwtUser.getPhone();
        String ip = RequestStringUtils.getIp(request);
        String browser = RequestStringUtils.getBrowser(request);
        String address = RequestStringUtils.getCityInfo(ip);
        OnlineUser onlineUser = null;
        try {
            onlineUser = new OnlineUser(jwtUser.getUsername(), phone, email, browser, ip, address, EncryptUtils.desEncrypt(token), new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisUtil.set(properties.getOnlineKey() + token, JSON.toJSONString(onlineUser), properties.getTokenValidityInSeconds() / 1000);
    }

    /**
     * 保存在线用户信息
     *
     * @param jwtUser /
     * @param token   /
     * @param request /
     */
    public void save(JwtUser jwtUser, String token, HttpServletRequest request) {
        String job = jwtUser.getDept() + "/" + jwtUser.getJob();
        String ip = RequestStringUtils.getIp(request);
        String browser = RequestStringUtils.getBrowser(request);
        String address = RequestStringUtils.getCityInfo(ip);
        OnlineUser onlineUser = null;
        try {
            onlineUser = new OnlineUser(jwtUser.getUsername(), jwtUser.getNickName(), job, browser, ip, address, EncryptUtils.desEncrypt(token), new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisUtil.set(properties.getOnlineKey() + token, JSON.toJSONString(onlineUser), properties.getTokenValidityInSeconds() / 1000);
    }


    /**
     * 踢出用户
     *
     * @param key /
     * @throws Exception /
     */
    public void kickOut(String key) throws Exception {
        key = properties.getOnlineKey() + EncryptUtils.desDecrypt(key);
        redisUtil.delete(key);
    }

    /**
     * 退出登录
     *
     * @param token /
     */
    public void logout(String token) {
        String key = properties.getOnlineKey() + token;
        redisUtil.delete(key);
    }

    /**
     * 查询用户
     *
     * @param key /
     * @return /
     */
    public OnlineUser getOne(String key) {
        return JSON.parseObject(redisUtil.get(key), OnlineUser.class);
    }

//    /**
//     * 检测用户是否在之前已经登录，已经登录踢下线
//     *
//     * @param userName 用户名
//     */
//    public void checkLoginOnUser(String userName, String igoreToken) {
//        List<OnlineUser> onlineUsers = getAll(userName);
//        if (onlineUsers == null || onlineUsers.isEmpty()) {
//            return;
//        }
//        for (OnlineUser onlineUser : onlineUsers) {
//            if (onlineUser.getUserName().equals(userName)) {
//                try {
//                    String token = EncryptUtils.desDecrypt(onlineUser.getKey());
//                    if (RequestStringUtils.isNotBlank(igoreToken) && !igoreToken.equals(token)) {
//                        this.kickOut(onlineUser.getKey());
//                    } else if (RequestStringUtils.isBlank(igoreToken)) {
//                        this.kickOut(onlineUser.getKey());
//                    }
//                } catch (Exception e) {
//                    log.error("checkUser is error", e);
//                }
//            }
//        }
//    }

}
